package com.tarena.rpc.demo01.consumer;

import com.tarena.rpc.common.People;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class PeopleProxy{
    public static People getPeople(){
        InvocationHandler handler=new InvocationHandler(){
            //在代理方法中建立底层连接
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //建立8000通信关系 通过序列化传递参数 反序列化解析返回结果
                //调用provider远程的people实现wash
                Socket socket=new Socket("127.0.0.1",8000);
                //输出流
                String clothName= (String) args[0];
                OutputStream outputStream = socket.getOutputStream();
                DataOutputStream dos=new DataOutputStream(outputStream);
                dos.writeUTF(clothName);
                dos.flush();
                //对方服务端 也有返回数据
                InputStream inputStream = socket.getInputStream();
                DataInputStream dis=new DataInputStream(inputStream);
                String result = dis.readUTF();
                return result;
            }
        };
        return (People) Proxy.newProxyInstance(People.class.getClassLoader(),new Class[]{People.class},handler);
    }
}
